const express = require('express');
const fs = require('fs');
const path = require('path');

const app = express();
// 解析post请求传递的参数
app.use(express.urlencoded({ extended: true }));

app.all('*', function (req, res, next) {
    // 设置可跨域访问
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

    if (req.method == 'OPTIONS') return res.send(200); // 让options请求快速返回
    next();
});

const loadRoutes = (routesDir) => {
    fs.readdir(routesDir, (err, files) => {
        if (err) {
            return console.error('Unable to scan directory: ' + err);
        }
        // 遍历所有文件
        files.forEach(file => {
            const filePath = path.join(routesDir, file);
            fs.stat(filePath, (err, stats) => {
                if (err) {
                    return console.error('Unable to get file info: ' + err);
                }
                // 判断是文件还是目录
                const isDirectory = stats.isDirectory()

                if (!isDirectory && !file.startsWith('.') && file.endsWith('.js')) {
                    const routePath = path.join(routesDir, file);

                    const routeName = file.replace('.js', '');
                    const routeModule = require(routePath);

                    // 根据文件名设置接口名
                    const segments = routeName.split(path.sep);
                    const lastSegment = segments[segments.length - 1];
                    let routeBasePath = '/' + lastSegment;

                    // 如果为qywx，加入/qywx前缀
                    const routesDirArr = routesDir.split('/')
                    let lastPath = routesDirArr[routesDirArr.length - 1]
                    lastPath === 'qywx' && (routeBasePath = '/' + lastPath + routeBasePath)

                    console.log('2222', isDirectory, routeBasePath)

                    app.use(routeBasePath, routeModule);
                }

                isDirectory && (loadRoutes(path.join(__dirname, 'routes/' + file)))
            });
        });
    });
}

// 根路由
loadRoutes(path.join(__dirname, 'routes'))

module.exports = app;
